/*
 * 文件名： QianDaoActivity.java
 * 描    述：签到
 * 时    间：2015-3-25 下午5:47:21
 * 版    本：V1.0
 */

package com.miguo.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.miguo.activity.base.BaseActivity;
import com.miguo.app.AppContext;
import com.miguo.app.AppHelper;
import com.miguo.component.BaseHeadView;
import com.miguo.framework.request.JsonData;
import com.miguo.framework.utils.Toast;
import com.miguo.framework.view.SwitchButton;
import com.miguo.framework.view.dialogs.fragment.SimpleDialogFragment;
import com.miguo.framework.view.scroll.OverScrollView;
import com.miguo.http.HttpClient;
import com.miguo.http.Url;
import com.miguo.http.callback.AjaxCallBack;
import com.miguo.ui.R;
import com.miguo.utils.SignAlarmUtils;
import com.miguo.view.CalendarMonthView;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class SignActivity extends BaseActivity implements OnClickListener {

    private CalendarMonthView mMonthView;
    private TextView mScoreTv, mDateTv, mLastDayTv, mRuleTv;
    private Button mSignBtn;
    private SwitchButton mRemind;
    private int totalScore = 0, addScore = 1;// 总积分和签到增加的积分
    private int lastDay = 0;//持续签到天数
    private int date = 1, moth = 0;
    private boolean isSignToday = false;
    private boolean isSignRecord = false;// 是否已经获取到了签到记录,避免重复获取

    private BaseHeadView mBaseHead;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign);
        initExtra();
        findViewById();
        initView();
    }

    private void initExtra() {
        Intent in = getIntent();
        if (in.getBooleanExtra("sign", false)) {
            isBack = false;
            isBackBtn = false;
            setSwipeBackEnable(false);
        }
    }

    private void findViewById() {
        mBaseHead = (BaseHeadView) findViewById(R.id.base_head);
        mBaseHead.setActivity(this);
        mBaseHead.setBackBtn(isBackBtn);
        mBaseHead.setTitle("签到");
        mBaseHead.getRightTextView().setText("积分商城");
        mBaseHead.getRightTextView().setVisibility(View.VISIBLE);
        mBaseHead.getRightTextView().setOnClickListener(this);

        OverScrollView scroll = (OverScrollView) findViewById(R.id.sign_integral_scroll);
        if (Build.VERSION.SDK_INT >= 9) {
            scroll.setOverScrollMode(View.OVER_SCROLL_NEVER);
        }

        mLastDayTv = (TextView) findViewById(R.id.sign_integral_last_day_tv);

        mDateTv = (TextView) findViewById(R.id.sign_date_tv);
        Calendar calendar = Calendar.getInstance();
        date = calendar.get(Calendar.DAY_OF_MONTH);
        moth = calendar.get(Calendar.MONTH) + 1;
        mDateTv.setText(calendar.get(Calendar.YEAR) + "年" + moth + "月" + date + "日");

        mScoreTv = (TextView) findViewById(R.id.sign_integral_tv);
        mRuleTv = (TextView) findViewById(R.id.sign_rule_tv);
        mRuleTv.setOnClickListener(this);

        mSignBtn = (Button) findViewById(R.id.sign_btn);
        mSignBtn.setEnabled(true);
        mSignBtn.setOnClickListener(this);

        mMonthView = (CalendarMonthView) findViewById(R.id.sign_calendar_month_view);

        // 签到提醒
        mRemind = (SwitchButton) findViewById(R.id.sign_integral_remind_bt);
        mRemind.setChecked(!AppContext.Prefs().getSignAlramSwitch());
        mRemind.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    AppContext.Prefs().setSignAlramSwitch(false);
                    SignAlarmUtils.unSignAlarm();
                } else {
                    AppContext.Prefs().setSignAlramSwitch(true);
                    SignAlarmUtils.signAlarm();
                }
            }
        });
    }

    // 根据签到状态初始化UI

    private void initView() {
        if (AppContext.UserInfo().getIsLogin()) {// 已登录
            // 判断今天是否签到
            if (isSignToday) {
                mScoreTv.setText(totalScore + "分");
                mSignBtn.setText("明日签到+" + addScore);
                mSignBtn.setBackgroundResource(R.drawable.shape_circle_grey_e2e0e1_bg);
                mSignBtn.setEnabled(false);
            } else {
                mScoreTv.setText(totalScore + "分");
                mSignBtn.setText("今日签到+" + addScore);
            }
        } else {// 未登录
            mScoreTv.setText("未登录");
            mSignBtn.setText("签到赚积分");
        }
        initLastDay();
    }

    private void initLastDay() {
        String str = lastDay + "天";
        SpannableString sb = new SpannableString(str);
        // 设置字体
        sb.setSpan(new AbsoluteSizeSpan(30, true), str.indexOf("天"),
                str.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mLastDayTv.setText(sb);
    }

    private void goSign() {
        AjaxCallBack callBack = new AjaxCallBack(mActivity, "努力加载中...") {
            @Override
            public void onRequestFinish(JsonData json) {
                super.onRequestFinish(json);
                if (json.optInt("status") == 200) {
                    JsonData data = json.optJson("data");
                    addScore = data.optInt("add_score");
                    totalScore = data.optInt("score");
                    lastDay = data.optInt("last_day");
                    isSignToday = true;
                    initView();
                    mMonthView.updateItem(date);
                    AppContext.Prefs().setSignTime(String.valueOf(System.currentTimeMillis()));
                } else {
                    Toast.show(mContext, json.optString("info"));
                }
            }
        };
        Map<String, String> param = new HashMap<String, String>();
        param.put("token", AppContext.UserInfo().getToken());
        HttpClient.postEncryptData(Url.toRoute(Url.Sign.Sign, 1), param, callBack);
    }

    private void queryRecord() {
        AjaxCallBack callBack = new AjaxCallBack(mActivity, "努力加载中...") {
            @Override
            public void onRequestFinish(JsonData json) {
                super.onRequestFinish(json);
                if (json.optInt("status") == 200) {
                    JsonData data = json.optJson("data");
                    if (1 == data.optInt("is_sign")) {
                        isSignToday = true;
                    }
                    totalScore = Integer
                            .parseInt(data.optString("total_score"));
                    addScore = data.optInt("add_score");
                    lastDay = data.optInt("last_day");

                    JsonData date = data.optJson("date");
                    for (int i = 0; i < date.length(); i++) {
                        int dates = date.optJson(i).optInt("date");
                        mMonthView.updateItem(dates);
                    }
                    initView();
                    isSignRecord = true;
                } else {
                    Toast.show(mContext, json.optString("info"));
                }
            }
        };

        Map<String, String> param = new HashMap<String, String>();
        param.put("token", AppContext.UserInfo().getToken());
        HttpClient
                .postEncryptData(Url.toRoute(Url.Sign.SignRecord, 1), param, callBack);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sign_btn:
                if (AppContext.UserInfo().getIsLogin()) {
                    if (!isSignToday) {
                        goSign();
                    }
                } else {
                    AppHelper.StartLogin(this);
                }
                break;
            case R.id.right_tv:
                // 跳转到积分商城
                AppHelper.StartScoreShop(this);
                break;
            case R.id.sign_rule_tv:
                SimpleDialogFragment.createBuilder(this, getSupportFragmentManager())
                        .setTitle(R.string.dialog_integral_rule)
                        .setMessage(R.string.dialog_integral_rule_text)
                        .show();
                break;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (AppContext.UserInfo().getIsLogin() && !isSignRecord) {
            queryRecord();
        }
    }

}
